<template>
  <div>
    <a-row :gutter="[8, 8]">
      <a-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <!-- 客户模块 -->
        <a-card title="客户" :loading="customer.loading" :bordered="false" :body-style="{ padding: '6' }">
          <template #extra><a @click="loadData(customer)"><a-icon type="sync" /></a></template>
          <a-row>
            <template v-for="rec in customer.dataSource">
              <a-col :span="rec.width">
                <head-info :title="rec.label" :content="formatInt(rec.value)" :center="true" />
              </a-col>
            </template>
          </a-row>
        </a-card>
      </a-col>
      <a-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <!-- 供应商模块 -->
        <a-card title="供应商" :loading="supplier.loading" :bordered="false" :body-style="{ padding: '6' }">
          <template #extra><a @click="loadData(supplier)"><a-icon type="sync" /></a></template>
          <a-row>
            <template v-for="rec in supplier.dataSource">
              <a-col :span="rec.width">
                <head-info :title="rec.label" :content="formatInt(rec.value)" :center="true" />
              </a-col>
            </template>
          </a-row>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="[8, 8]" style="margin-top: 16px;">
      <a-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <!-- 其他支出（类型）模块 -->
        <a-card :loading="financeSummary.loading" :bordered="false" :body-style="{ padding: '0' }">
          <div style="display: flex; align-items: center; padding: 12px 16px; border-bottom: 1px solid #f0f0f0;">
            <div style="font-weight: 500; font-size: 16px; margin-right: 50px;">其他支出（类型）</div>
            <div style="display: flex; align-items: center; margin-right: 16px;">
              <span style="margin-right: 8px;">日期范围：</span>
              <j-date placeholder="请选择开始" style="width: 150px; margin-right: 8px;" v-model="financeBeginDate" dateFormat="YYYY-MM-DD"/>
              <span style="margin: 0 4px;">-</span>
              <j-date placeholder="请选择结束" style="width: 150px; margin-right: 16px;" v-model="financeEndDate" dateFormat="YYYY-MM-DD"/>
            </div>
            <a @click="loadData(financeSummary)" style="white-space: nowrap;"><a-icon type="sync" />查询</a>
          </div>
          <div style="padding: 16px;">
          <a-row>
            <template v-if="financeSummary.dataSource && financeSummary.dataSource.length > 0">
              <template v-for="rec in financeSummary.dataSource">
                <a-col :xl="6" :lg="6" :md="6" :sm="12" :xs="12">
                  <a-card-grid style="height: 100%; display: flex; justify-content: center; align-items: center; padding: 24px 16px;" :bordered="false">
                    <div>
                      <h4 style="font-size: 16px; margin-bottom: 16px;">{{rec.payType_dictText}}</h4>
                      <div style="font-size: 20px; font-weight: bold; ">¥ {{formatAmt(rec.amount)}}</div>
                    </div>
                  </a-card-grid>
                </a-col>
              </template>
            </template>
            <a-empty v-else :description="'暂无数据'" style="width: 100%;" />
          </a-row>
          </div>
        </a-card>
      </a-col>

      <!-- 其他模块... -->
      <a-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <a-card title="其他支出" :loading="otherExpense.loading" :bordered="false">
          <template #extra>
            <div style="display: flex; align-items: center;">
              <j-date placeholder="开始日期" v-model="beginDate" style="width: 120px;" dateFormat="YYYY-MM-DD" />
              <span style="margin: 0 8px;">至</span>
              <j-date placeholder="结束日期" v-model="endDate" style="width: 120px;" dateFormat="YYYY-MM-DD" />
              <a-button type="primary" size="small" @click="loadData(otherExpense)" style="margin-left: 8px;">
                查询
              </a-button>
            </div>
          </template>
          <area-chart-ty
            :dataSource="otherExpense.dataSource"
            x="date"
            y="金额"
            :loading="otherExpense.loading"
            :height="300"
            scale="date"
          />
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
  import HeadInfo from '@/components/tools/HeadInfo'
  import AreaChartTy from '@/components/chart/AreaChartTy'
  import XEUtils from "xe-utils"

  export default {
    name: "ProfitAnalysis",
    components: { HeadInfo, AreaChartTy },
    data() {
      return {
        // 查询参数
        monthQuery: '',
        beginDate: '',
        endDate: '',
        // 财务概览独立的日期范围
        financeBeginDate: '',
        financeEndDate: '',
        
        // 客户模块数据
        customer: {
          url: '/wrapper/cgreport/getData/1580740609854935042',
          loading: false,
          dataSource: [],
        },
        
        // 供应商模块数据
        supplier: {
          url: '/wrapper/cgreport/getData/1580740795561938946',
          loading: false,
          dataSource: [],
        },
        
        // 其他支出数据
        otherExpense: {
          url: '/erp/finance/financeSummary/queryExpense',
          loading: false,
          dataSource: []
        },
        
        // 财务概览数据
        financeSummary: {
          url: '/erp/finance/financeSummary/queryExpenseByType',
          loading: false,
          dataSource: []
        }
      }
    },

    created() {
      // 设置默认日期范围：当前年份的1月到当前月
      const now = new Date();
      const currentYear = now.getFullYear();
      const currentMonth = now.getMonth() + 1;
      
      // 开始日期：当前年份的1月1日
      this.beginDate = `${currentYear}-01-01`;
      this.financeBeginDate = `${currentYear}-01-01`;
      
      // 结束日期：当前月的最后一天
      const lastDayOfCurrentMonth = new Date(currentYear, currentMonth, 0).getDate();
      const formattedMonth = currentMonth.toString().padStart(2, '0');
      const formattedDay = lastDayOfCurrentMonth.toString().padStart(2, '0');
      this.endDate = `${currentYear}-${formattedMonth}-${formattedDay}`;
      this.financeEndDate = `${currentYear}-${formattedMonth}-${formattedDay}`;
      
      // 初始化加载数据
      this.loadData(this.customer);
      this.loadData(this.supplier);
      this.loadData(this.otherExpense);
      this.loadData(this.financeSummary);
    },

    methods: {
      loadData(data) {
        data.loading = true;
        let params = {};
        
        if (data === this.otherExpense) {
          if (this.beginDate) {
            params.beginDate = this.beginDate;
          }
          if (this.endDate) {
            params.endDate = this.endDate;
          }
          this.$http.get(data.url, { params }).then(res => {
            if (res.result) {
              data.dataSource = res.result.map(item => ({
                date: item.date,
                y: item.amount,
                amount: item.amount
              }));
            }
          }).finally(() => {
            data.loading = false;
          });
        } else if (data === this.financeSummary) {
          params = {};
          if (this.financeBeginDate) {
            params.beginDate = this.financeBeginDate;
          }
          if (this.financeEndDate) {
            params.endDate = this.financeEndDate;
          }
          this.$http.get(data.url, { params }).then(res => {
            if (res.result) {
              data.dataSource = res.result;
            }
          }).finally(() => {
            data.loading = false;
          });
        } else {
          // 客户和供应商模块直接调用原始接口
          this.$http.get(data.url)
            .then(res => data.dataSource = res.result.records)
            .finally(() => data.loading = false);
        }
      },

      formatAmt(amt) {
        return XEUtils.commafy(amt || 0, { digits: 2 }).toString();
      },

      formatInt(i) {
        return XEUtils.commafy(i || 0, { digits: 0 }).toString();
      }
    }
  }
</script>

<style scoped>
</style>